//! 简化的Tokio网络层实现
//! 
//! 核心设计：
//! 1. Tokio监听TCP连接，获得TcpStream
//! 2. 将TcpStream包装为实现NetworkStream trait的SimpleTokioStream
//! 3. 直接传递给协议层的handle_connection_stream函数
//! 4. 协议层完全接管网络流对象，使用异步I/O

use std::sync::atomic::AtomicU64;
use std::io;
use tokio::net::{TcpStream, TcpListener};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use std::sync::atomic::Ordering;
use async_trait::async_trait;
use crate::core::network::{AsyncNetworkStream, LightweightRuntime};
use crate::protocol::AbstractedProtocolHandler;
use crate::storage::GlobalStorageManager;
use crate::event::ConnectionId;

/// Tokio网络流适配器
/// 
/// 直接使用Tokio TcpStream提供异步NetworkStream接口
/// 保持异步一致性，提供更好的性能
#[derive(Debug)]
pub struct SimpleTokioStream {
    /// 内部的Tokio TcpStream
    stream: TcpStream,
    /// 远程地址
    remote_addr: String,
}

impl SimpleTokioStream {
    /// 从Tokio TcpStream创建适配器
    pub fn from_tokio_stream(tokio_stream: TcpStream) -> io::Result<Self> {
        let remote_addr = tokio_stream.peer_addr()
            .map(|addr| addr.to_string())
            .unwrap_or_else(|_| "unknown".to_string());
        
        Ok(Self {
            stream: tokio_stream,
            remote_addr,
        })
    }
}

#[async_trait]
impl AsyncNetworkStream for SimpleTokioStream {
    async fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.stream.read(buf).await
    }
    
    async fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.stream.write(buf).await
    }
    
    async fn flush(&mut self) -> io::Result<()> {
        self.stream.flush().await
    }
    
    fn is_connected(&self) -> bool {
        // 简单检查：尝试获取peer地址
        self.stream.peer_addr().is_ok()
    }
    
    fn remote_addr(&self) -> Option<String> {
        Some(self.remote_addr.clone())
    }
    
    async fn shutdown(&mut self) -> io::Result<()> {
        self.stream.shutdown().await
    }
    
    fn network_type(&self) -> &'static str {
        "Tokio-TCP"
    }
}

/// 简化的Tokio运行时
#[derive(Debug)]
pub struct SimpleTokioRuntime {
    task_counter: AtomicU64,
}

impl Default for SimpleTokioRuntime {
    fn default() -> Self {
        Self::new()
    }
}

impl SimpleTokioRuntime {
    pub fn new() -> Self {
        Self {
            task_counter: AtomicU64::new(0),
        }
    }
}

impl LightweightRuntime for SimpleTokioRuntime {
    fn spawn_task<F>(&self, task: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let _task_id = self.task_counter.fetch_add(1, Ordering::SeqCst);
        
        // 在当前线程执行（简化实现）
        task();
    }
    
    fn lightweight_type(&self) -> &'static str {
        "SimpleTokio"
    }
}

/// 简化的Tokio Redis服务器
/// 
/// 核心职责：
/// 1. 使用Tokio监听TCP连接
/// 2. 为每个连接创建SimpleTokioStream
/// 3. 直接调用协议层的handle_connection_stream
pub struct SimpleTokioRedisServer {
    bind_addr: String,
    connection_counter: AtomicU64,
}

impl SimpleTokioRedisServer {
    pub fn new(bind_addr: String) -> Self {
        Self {
            bind_addr,
            connection_counter: AtomicU64::new(0),
        }
    }
    
    pub async fn start(&self) -> io::Result<()> {
        // 初始化全局共享存储
        GlobalStorageManager::initialize();
        
        let listener = TcpListener::bind(&self.bind_addr).await?;
        
        loop {
            match listener.accept().await {
                Ok((stream, _addr)) => {
                    let connection_id = self.connection_counter.fetch_add(1, Ordering::SeqCst);
                    
                    // 在新的tokio任务中处理连接
                    tokio::spawn(async move {
                        if let Err(_e) = Self::handle_connection(connection_id, stream).await {
                            // eprintln!("❌ 连接 {} 处理错误: {}", connection_id, e);
                        }
                        // println!("🔌 连接 {} 已断开", connection_id);
                    });
                }
                Err(_e) => {
                    // eprintln!("❌ 接受连接失败: {}", e);
                    continue;
                }
            }
        }
    }
    
    async fn handle_connection(connection_id: ConnectionId, stream: TcpStream) -> io::Result<()> {
        // 1. 将TcpStream包装为NetworkStream
        let network_stream = SimpleTokioStream::from_tokio_stream(stream)?;
        
        // 2. 创建运行时
        let runtime = SimpleTokioRuntime::new();
        
        // 3. 创建协议处理器
        let mut protocol_handler = AbstractedProtocolHandler::new(connection_id, runtime);
        
        // 4. **关键步骤**：直接异步调用协议层的handle_connection_stream
        //    协议层使用全局共享存储，不再需要单独的存储分发器
        let result = protocol_handler.handle_connection_stream(
            Box::new(network_stream),
        ).await;
        
        match result {
            Ok(()) => {
                // println!("✅ 连接 {} 协议处理正常完成", connection_id);
            }
            Err(_e) => {
                // eprintln!("❌ 连接 {} 协议处理失败: {:?}", connection_id, e);
            }
        }
        
        // 5. 清理资源（只需要关闭协议处理器）
        if let Err(_e) = protocol_handler.close() {
            // eprintln!("❌ 连接 {} 关闭协议处理器失败: {:?}", connection_id, e);
        }
        
        Ok(())
    }
}

/// 启动简单的Tokio Redis服务器
/// 
/// 创建并启动SimpleTokioRedisServer的便捷函数
pub async fn start_simple_tokio_redis_server(bind_addr: &str) -> io::Result<()> {
    let server = SimpleTokioRedisServer::new(bind_addr.to_string());
    server.start().await
}